<template>
  <div class="app-container">
    <el-form label-width="120px">
      <el-form-item label="参数类型">
        <el-select v-model="param.typee" clearable placeholder="请选择">
          <el-option :value="1" label="key-value类型"/>
          <el-option :value="2" label="SQL类型"/>
        </el-select>
      </el-form-item>
      <el-form-item label="参数名称">
        <el-input v-model="param.name"/>
      </el-form-item>
      <el-form-item label="参数值">
        <el-input v-model="param.value"/>
      </el-form-item>
      <el-form-item label="参数环境">
        <el-select v-model="param.environment" clearable placeholder="请选择">
          <el-option :value="1" label="dev"/>
          <el-option :value="2" label="test"/>
          <el-option :value="3" label="online"/>
        </el-select>
      </el-form-item>
      <el-form-item label="参数说明">
        <el-input v-model="param.description" :rows="7" type="textarea"/>
      </el-form-item>

      <el-form-item>
        <el-button :disabled="saveBtnDisabled" type="primary" @click="saveOrUpdate()">保存</el-button>
      </el-form-item>
    </el-form>
  </div>
</template>

<script>
import param from '@/api/param'
export default {
  data() {
    return {
      param: {
        typee: 1,
        environment: 1
      },
      saveBtnDisabled: false // 保存按钮是否禁用,
    }
  },
  created() {
    this.init()
  },
  watch: {
    $route(to, from) { // 检测路由状态
      this.init()
    }
  },
  methods: {
    init() {
      if (this.$route.params && this.$route.params.id) {
        const id = this.$route.params.id;
        this.getParamById(id);
      } else {
        this.param = {};
      }
    },
    getParamById(id) {
      param.getById(id).then(response => {
        this.param = response.data.item;
        console.log(this.param)
      }).catch(response => {});
    },
    saveOrUpdate() {
      if (this.param.typee == null || this.param.name == null || this.param.value == null || this.param.environment == null) {
        this.$message({
          type: 'error',
          message: '信息填充不完整!'
        })
      } else {
        if (this.param.id) {
          this.updateData()
        } else {
          this.saveData()
        }
      }
    },
    saveData() {
      param.save(this.param).then(response => {
        this.$message({
          type: 'success',
          message: '添加成功!'
        })
        this.$router.push({ path: '/param/list' })
      })
    },
    updateData() {
      this.saveBtnDisabled = true;
      param.updateParam(this.param).then(response => {
        this.$message({
          type: "success",
          message: "修改成功!",
        });
        this.$router.push({ path: "/param/list" });
      }).catch((response) => {});
    }
  }
}
</script>